package com.business_clean.app.weight.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.view.WheelOptions;
import com.business_clean.R;
import com.business_clean.app.callback.OnDialogCityIdPickerListener;
import com.business_clean.app.callback.OnDialogCityPickerListener;
import com.business_clean.app.callback.ProviceCityAreaDataCallBack;
import com.business_clean.app.config.AsyncRequestUtil;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.data.initconfig.city.ProviceCityAreaData;
import com.contrarywind.view.WheelView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;

import java.util.ArrayList;
import java.util.List;


public class CustomCityPickerPopup extends BottomPopupView {
    private String title;
    private String curProvice;
    private String curCity;
    private String curArea;

    public CustomCityPickerPopup setTitle(String title) {
        this.title = title;
        return this;
    }

    public CustomCityPickerPopup setDefData(String curProvice, String curCity, String curArea) {
        this.curProvice = curProvice;
        this.curCity = curCity;
        this.curArea = curArea;
        return this;
    }

    public enum Mode {
        PCA, PC
    }

    private Mode mode = Mode.PCA;
    private List<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private List<String> id1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> id2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> id3Items = new ArrayList<>();

    private OnDialogCityPickerListener cityPickerListener;
    private OnDialogCityIdPickerListener cityIdPickerListener;
    private WheelOptions wheelOptions;
    public int dividerColor = 0xFFd5d5d5; //分割线的颜色
    public float lineSpace = 2.4f; // 条目间距倍数 默认2
    public int textColorOut = 0xFFa8a8a8; //分割线以外的文字颜色
    public int textColorCenter = 0xFF2a2a2a; //分割线之间的文字颜色

    public CustomCityPickerPopup(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.common_popup_city_picker;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        ((TextView) findViewById(R.id.tv_common_dialog_center)).setText(title);

        findViewById(R.id.tv_common_dialog_cancel).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        TextView btnConfirm = findViewById(R.id.tv_common_dialog_yes);
        btnConfirm.setTextColor(XPopup.getPrimaryColor());
        btnConfirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cityPickerListener != null) {
                    int[] optionsCurrentItems = wheelOptions.getCurrentItems();
                    int options1 = optionsCurrentItems[0];
                    int options2 = optionsCurrentItems[1];
                    int options3 = optionsCurrentItems[2];
                    if (options1 >= 0 && options1 < options1Items.size() &&
                            options1 < options2Items.size() && options2 >= 0 && options2 < options2Items.get(options1).size() &&
                            options1 < options3Items.size() && options2 < options3Items.get(options1).size() && options3 >= 0 && options3 < options3Items.get(options1).get(options2).size()) {

                        cityPickerListener.onCityConfirm(options1Items.get(options1),
                                options2Items.get(options1).get(options2),
                                options3Items.get(options1).get(options2).get(options3), options1, options2, options3, v);

                        if (cityIdPickerListener != null) {
                            cityIdPickerListener.onCityConfirm(id1Items.get(options1),
                                    id2Items.get(options1).get(options2), id3Items.get(options1).get(options2).get(options3));
                        }
                    }
                }
                dismiss();
            }
        });

        wheelOptions = new WheelOptions(findViewById(R.id.citypicker), true);
        if (cityPickerListener != null) {
            wheelOptions.setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                @Override
                public void onOptionsSelectChanged(int options1, int options2, int options3) {
                    if (options1 >= options1Items.size()) return;
                    if (options1 >= options2Items.size() || options2 >= options2Items.get(options1).size())
                        return;
                    if (options1 >= options3Items.size() || options2 >= options3Items.get(options1).size()
                            || options3 >= options3Items.get(options1).get(options2).size()) return;
                    String province = options1Items.get(options1);
                    String city = options2Items.get(options1).get(options2);
                    String area = options3Items.get(options1).get(options2).get(options3);
                    cityPickerListener.onCityChange(province, city, area);
                }
            });
        }
        wheelOptions.setTextContentSize(18);
        wheelOptions.setItemsVisible(7);
        wheelOptions.setAlphaGradient(true);
        wheelOptions.setCyclic(false);

        wheelOptions.setDividerColor(dividerColor);
        wheelOptions.setDividerType(WheelView.DividerType.FILL);
        wheelOptions.setLineSpacingMultiplier(lineSpace);
        wheelOptions.setTextColorOut(textColorOut);
        wheelOptions.setTextColorCenter(textColorCenter);
        wheelOptions.isCenterLabel(false);

        if (!options1Items.isEmpty() && !options2Items.isEmpty() && !options3Items.isEmpty()) {
            //有数据直接显示
            if (wheelOptions != null) {
                fillWheelData();
            }
        } else {
            initJsonData();
        }
    }

    private void fillWheelData() {
        if (mode == Mode.PCA) {
            wheelOptions.setPicker(options1Items, options2Items, options3Items);
        } else {
            wheelOptions.setPicker(options1Items, options2Items, null);
        }
        try {
            int indexProvice = options1Items.indexOf(curProvice);
            int indexCity = options2Items.get(indexProvice).indexOf(curCity);
            int indexArea = options3Items.get(indexProvice).get(indexCity).indexOf(curArea);
            wheelOptions.setCurrentItems(indexProvice, indexCity, indexArea);
        } catch (Exception e) {
            wheelOptions.setCurrentItems(0, 0, 0);
        }
    }

    public CustomCityPickerPopup setMode(Mode mode) {
        this.mode = mode;
        return this;
    }

    public CustomCityPickerPopup setCityPickerListener(OnDialogCityPickerListener listener) {
        this.cityPickerListener = listener;
        return this;
    }

    public CustomCityPickerPopup setCityIdPickerListener(OnDialogCityIdPickerListener listener) {
        this.cityIdPickerListener = listener;
        return this;
    }

    private void initJsonData() {//解析数据
        final String cityDataJson = MMKVHelper.getString(ConstantMMVK.PROVICE_CITY_AREA_DATA);
        if (!TextUtils.isEmpty(cityDataJson)) {
            List<ProviceCityAreaData> cityDatas = JSON.parseArray(cityDataJson, ProviceCityAreaData.class);
            initData(cityDatas);
        } else {
            AsyncRequestUtil.requestProviceCityArea(new ProviceCityAreaDataCallBack() {
                @Override
                public void cityDataCallBack(List<ProviceCityAreaData> list) {
                    List<ProviceCityAreaData> cityDatas = list;
                    initData(cityDatas);
                }
            });
        }
    }

    private void initData(List<ProviceCityAreaData> jsonBean) {
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
//        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            options1Items.add(jsonBean.get(i).getName());
            id1Items.add(jsonBean.get(i).getId());
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> areaList = new ArrayList<>();//该省的所有地区列表（第三极）

            ArrayList<String> cityIdList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> areaIdList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getList().size(); c++) {//遍历该省份的所有城市
                cityList.add(jsonBean.get(i).getList().get(c).getName());//添加城市
                cityIdList.add(jsonBean.get(i).getList().get(c).getId());
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                ArrayList<String> city_AreaIdList = new ArrayList<>();//该城市的所有地区列表

                for (int d = 0; d < jsonBean.get(i).getList().get(c).getList().size(); d++) {
                    city_AreaList.add(jsonBean.get(i).getList().get(c).getList().get(d).getName());
                    city_AreaIdList.add(jsonBean.get(i).getList().get(c).getList().get(d).getId());
                }
                areaList.add(city_AreaList);//添加该省所有地区数据
                areaIdList.add(city_AreaIdList);
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
            id2Items.add(cityIdList);

            /**
             * 添加地区数据
             */
            options3Items.add(areaList);
            id3Items.add(areaIdList);
        }
        fillWheelData();
//        wheelOptions.setPicker(options1Items, options2Items, options3Items);
//        wheelOptions.setCurrentItems(0, 0, 0);
    }
}
